package edu.bw.advice;

import edu.bw.utils.TransactionManager;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Log4j2
@Aspect
public class TransactionAdvice {

    @Autowired
    private TransactionManager transactionManager;

    @Around("execution(* edu.bw.service..*.*(..)) " +
            "&& !execution(* edu.bw.service..*.find*(..))"+
            "&& !execution(* edu.bw.service..*.query*(..))")
    public Object aroundServiceAdvice(ProceedingJoinPoint pjp){
        Object retVal=null;

        try {
            transactionManager.beginTransaction();
            log.info("开启事务");
            log.info("执行{}目标方法",pjp.getSignature());

            retVal = pjp.proceed();//执行目标方法

            transactionManager.commit();
            log.info("提交事务");
        } catch (Throwable e) {
            transactionManager.rollback();
            log.info("回滚事务");
            throw new RuntimeException(e);
        }finally{
            transactionManager.release();
            log.info("释放资源");
        }
        return retVal;
    }




}
